package io.renren.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StrUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.ApplicationEntity;
import io.renren.entity.ParticipantEntity;
import io.renren.entity.RoomEntity;
import io.renren.entity.RoomEslEntity;
import io.renren.param.ApplicationSaveParam;
import io.renren.param.SetContentParam;
import io.renren.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 会议室申请记录
 *
 * @author 1
 * @email 1@2.com
 * @date 2021-08-19 11:56:03
 */
@RestController
@RequestMapping("/application")
@Validated
@Slf4j
public class ApplicationController {


    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private ParticipantService participantService;

    @Autowired
    private EslContentService eslContentService;

    @Autowired
    private RoomEslService roomEslService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {

        PageUtils page = applicationService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        ApplicationEntity application = applicationService.getById(id);

        return R.ok().put("application", application);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @Validated
    @Transactional
    public R save(@RequestBody ApplicationSaveParam param) {

        if (DateUtil.compare(param.getStartTime(), new Date()) < 0) {
            log.error("开始时间{}不能小于当前时间", param.getStartTime());
            throw new RRException("开始时间不能小于当前时间");
        }
        if (param.getEndTime() != null && DateUtil.compare(param.getStartTime(), param.getEndTime()) > 0) {
            log.error("开始时间{}不能大于结束时间{}", param.getStartTime(), param.getEndTime());
            throw new RRException("开始时间不能大于结束时间");
        }

        ApplicationEntity application = ApplicationEntity.convertFor(param);
        RoomEntity roomEntity = roomService.getById(application.getRoomId());
        if (roomEntity == null) {
            log.error("根据id{}查不到会议室", application.getRoomId());
            return R.error("根据id查不到会议室");
        }

        List<ApplicationEntity> unfinishApplications = applicationService.queryUnfinish(roomEntity.getId());
        for (ApplicationEntity unfinishApplication : unfinishApplications) {
            if (DateUtil.compare(param.getStartTime(), unfinishApplication.getStartTime()) > 0
                    && DateUtil.compare(param.getStartTime(), unfinishApplication.getEndTime()) < 0 //预约的开始时间在 已约会议的时间段内
                    ||
                    DateUtil.compare(param.getEndTime(), unfinishApplication.getStartTime()) > 0
                            && DateUtil.compare(param.getEndTime(), unfinishApplication.getEndTime()) < 0 //预约的结束时间在 已约会议的时间段内
                    ||
                    DateUtil.compare(unfinishApplication.getStartTime(), param.getStartTime()) > 0
                            && DateUtil.compare(unfinishApplication.getStartTime(), param.getEndTime()) < 0 //已约会议的开始时间在 预约的时间段内
                    ||
                    DateUtil.compare(unfinishApplication.getEndTime(), param.getStartTime()) > 0
                            && DateUtil.compare(unfinishApplication.getEndTime(), param.getEndTime()) < 0 //已约会议的结束时间在 预约的时间段内
            ) {
                log.error("会议室 {}在{}~{}内已有其他预定", roomEntity.getName(), DateUtil.format(param.getStartTime(), DatePattern.NORM_DATETIME_FORMAT), DateUtil.format(param.getEndTime(), DatePattern.NORM_DATETIME_FORMAT));
                throw new RRException("该时间段已被预定");
            }
        }

        applicationService.save(application);

        List<ApplicationEntity> applications = applicationService.queryByRoomIdAndSubject(roomEntity.getId(), param.getSubject());
        List<RoomEslEntity> roomEslEntities = roomEslService.queryByRoomIdAndType(roomEntity.getId(), "namePlate");


        String[] ps = new String[0];
        if (CollectionUtil.isNotEmpty(applications) && StringUtils.isNotBlank(param.getParticipants())) {
            String participants = param.getParticipants();
            ps = participants.split(";|,|；|，|、");
        }

        //设置铭牌信息
        if (ps.length > 0) {
            List<String> names = new ArrayList<>();
            for (String p : ps) {
                //铭牌名输入2个汉字时，自动在名字中间加空格，跟三个汉字的名字左右对齐
                String name = StrUtils.nameAutoFill(p);
                names.add(name);
            }

            //记录与会人
            participantService.bookApplication(roomEntity.getId(), applications.get(0).getId(), names);


            List<SetContentParam> setContentParams = new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("applicationId", String.valueOf(applications.get(0).getId()));
            PageUtils pageUtils1 = participantService.queryPage(map1);
            List<ParticipantEntity> participantEntities = (List<ParticipantEntity>) pageUtils1.getList();
            if (CollectionUtil.isNotEmpty(participantEntities)) {
//                int aliasNum = roomEslEntities.size() % 2 + roomEslEntities.size() / 2;
//                Integer max = aliasNum > participantEntities.size() ? participantEntities.size() : aliasNum;
                int max = participantEntities.size() * 2;
                int j = 0;
                for (int i = 0; i < max; i = i + 2) {
                    int nextEslIndex = i + 1;
                    if (nextEslIndex < roomEslEntities.size()) {
                        SetContentParam setContentParam = new SetContentParam();
                        SetContentParam setContentParam1 = new SetContentParam();
                        setContentParam.setName(names.get(j));
                        setContentParam1.setName(names.get(j));
                        setContentParam.setApplicationId(String.valueOf(applications.get(0).getId()));
                        setContentParam1.setApplicationId(String.valueOf(applications.get(0).getId()));
                        //一个与会人刷两个铭牌
                        setContentParam.setEslId(roomEslEntities.get(i).getEslId());
                        setContentParam1.setEslId(roomEslEntities.get(nextEslIndex).getEslId());
                        setContentParams.add(setContentParam);
                        setContentParams.add(setContentParam1);

                        j++;
                    }
                }
                if (CollectionUtil.isNotEmpty(setContentParams)) {
                    eslContentService.setContent(setContentParams);
                }
            }
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody ApplicationEntity application) {
        ValidatorUtils.validateEntity(application);
        applicationService.updateById(application);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        log.debug("cancel meeting_room booking params: {}", StringUtils.join(ids, ";"));

        if (ArrayUtils.isEmpty(ids)) {
            return R.error("请选择要取消的会议");
        }

        return applicationService.cancel(new HashSet<>(Arrays.asList(ids)));
    }
}
